<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="concurrent,ThreadPool," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言前段时间写过一篇《线程池没你想的那么简单》，和大家一起撸了一个基本的线程池，具备：

线程池基本调度功能。
线程池自动扩容缩容。
队列缓存线程。
关闭线程池。">
<meta property="og:type" content="article">
<meta property="og:title" content="线程池没你想的那么简单（续）">
<meta property="og:url" content="http://crossoverjie.top/2019/06/06/concurrent/threadpool-02/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言前段时间写过一篇《线程池没你想的那么简单》，和大家一起撸了一个基本的线程池，具备：

线程池基本调度功能。
线程池自动扩容缩容。
队列缓存线程。
关闭线程池。">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fff98dd9f45508.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fffa58a8081569.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fffb21f8d45495.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fffbe663629607.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fffc8161b82626.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fffd0634612268.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fffd755d053986.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7fffe1162589733.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7ffff5b48143266.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf7ffffe7dac41090.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf80005766ef25838.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf80006c916e52248.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf8000749e6c64762.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf800079d51a22414.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf8000823ad870419.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf8000872d1f43610.jpg">
<meta property="og:image" content="https://i.loli.net/2019/06/06/5cf80008d46e642627.jpg">
<meta property="og:updated_time" content="2019-06-05T18:02:36.680Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="线程池没你想的那么简单（续）">
<meta name="twitter:description" content="前言前段时间写过一篇《线程池没你想的那么简单》，和大家一起撸了一个基本的线程池，具备：

线程池基本调度功能。
线程池自动扩容缩容。
队列缓存线程。
关闭线程池。">
<meta name="twitter:image" content="https://i.loli.net/2019/06/06/5cf7fff98dd9f45508.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2019/06/06/concurrent/threadpool-02/"/>

  <title> 线程池没你想的那么简单（续） | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                线程池没你想的那么简单（续）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2019-06-06T08:10:00+08:00" content="2019-06-06">
              2019-06-06
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/并发/" itemprop="url" rel="index">
                    <span itemprop="name">并发</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2019/06/06/concurrent/threadpool-02/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2019/06/06/concurrent/threadpool-02/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2019/06/06/concurrent/threadpool-02/" class="leancloud_visitors" data-flag-title="线程池没你想的那么简单（续）">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/06/06/5cf7fff98dd9f45508.jpg" alt=""></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>前段时间写过一篇<a href="https://crossoverjie.top/2019/05/20/concurrent/threadpool-01/">《线程池没你想的那么简单》</a>，和大家一起撸了一个基本的线程池，具备：</p>
<ul>
<li>线程池基本调度功能。</li>
<li>线程池自动扩容缩容。</li>
<li>队列缓存线程。</li>
<li>关闭线程池。</li>
</ul>
<a id="more"></a>
<p>这些功能，最后也留下了三个待实现的 <code>features</code> 。</p>
<ul>
<li>执行带有返回值的线程。</li>
<li>异常处理怎么办？</li>
<li>所有任务执行完怎么通知我？</li>
</ul>
<p>这次就实现这三个特性来看看 <code>j.u.c</code> 中的线程池是如何实现这些需求的。</p>
<blockquote>
<p>再看本文之前，强烈建议先查看上文<a href="https://crossoverjie.top/2019/05/20/concurrent/threadpool-01/">《线程池没你想的那么简单》</a></p>
</blockquote>
<h1 id="任务完成后的通知"><a href="#任务完成后的通知" class="headerlink" title="任务完成后的通知"></a>任务完成后的通知</h1><p>大家在用线程池的时候或多或少都会有这样的需求：</p>
<p>线程池中的任务执行完毕后再通知主线程做其他事情，比如一批任务都执行完毕后再执行下一波任务等等。</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7fffa58a8081569.jpg" alt=""></p>
<p>以我们之前的代码为例：</p>
<blockquote>
<p>总共往线程池中提交了 13 个任务，直到他们都执行完毕后再打印 “任务执行完毕” 这个日志。</p>
</blockquote>
<p>执行结果如下：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7fffb21f8d45495.jpg" alt=""></p>
<p>为了简单的达到这个效果，我们可以在初始化线程池的时候传入一个接口的实现，这个接口就是用于任务完成之后的回调。</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7fffbe663629607.jpg" alt=""></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Notify</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 回调</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">notifyListen</span><span class="params">()</span> </span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>以上就是线程池的构造函数以及接口的定义。</p>
<p>所以想要实现这个功能的关键是在何时回调这个接口？</p>
<p>仔细想想其实也简单：只要我们记录提交到线程池中的任务及完成的数量，他们两者的差为 0 时就认为线程池中的任务已执行完毕；这时便可回调这个接口。</p>
<p>所以在往线程池中写入任务时我们需要记录任务数量：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7fffc8161b82626.jpg" alt=""></p>
<p>为了并发安全的考虑，这里的计数器采用了原子的 <code>AtomicInteger</code> 。</p>
<hr>
<p><img src="https://i.loli.net/2019/06/06/5cf7fffd0634612268.jpg" alt=""></p>
<p>而在任务执行完毕后就将计数器 -1 ，一旦为 0 时则任务任务全部执行完毕；这时便可回调我们自定义的接口完成通知。</p>
<hr>
<h2 id="JDK-的实现"><a href="#JDK-的实现" class="headerlink" title="JDK 的实现"></a>JDK 的实现</h2><p>这样的需求在 jdk 中的 <code>ThreadPoolExecutor</code> 中也有相关的 <code>API</code> ，只是用法不太一样，但本质原理都大同小异。</p>
<p>我们使用 <code>ThreadPoolExecutor</code> 的常规关闭流程如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">executorService.shutdown();</div><div class="line"><span class="keyword">while</span> (!executorService.awaitTermination(<span class="number">100</span>, TimeUnit.MILLISECONDS)) &#123;</div><div class="line">    logger.info(<span class="string">"thread running"</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>线程提交完毕后执行 <code>shutdown()</code> 关闭线程池，接着循环调用 <code>awaitTermination()</code> 方法，一旦任务全部执行完毕后则会返回 <code>true</code> 从而退出循环。</p>
<p>这两个方法的目的和原理如下：</p>
<ul>
<li>执行 <code>shutdown()</code> 后会将线程池的状态置为关闭状态，这时将会停止接收新的任务同时会等待队列中的任务全部执行完毕后才真正关闭线程池。</li>
<li><code>awaitTermination</code> 会阻塞直到线程池所有任务执行完毕或者超时时间已到。</li>
</ul>
<p>为什么要两个 <code>api</code> 结合一起使用呢？</p>
<p>主要还在最终的目的是：所有线程执行完毕后再做某件事情，也就是在线程执行完毕之前其实主线程是需要<strong>被阻塞</strong>的。</p>
<p><code>shutdown()</code> 执行后并不会阻塞，会立即返回，所有才需要后续用循环不停的调用 <code>awaitTermination()</code>，因为这个 api 才会阻塞线程。</p>
<p>其实我们查看源码会发现，<code>ThreadPoolExecutor</code> 中的阻塞依然也是等待通知机制的运用，只不过用的是 <code>LockSupport</code> 的 <code>API</code> 而已。</p>
<h1 id="带有返回值的线程"><a href="#带有返回值的线程" class="headerlink" title="带有返回值的线程"></a>带有返回值的线程</h1><p>接下来是带有返回值的线程，这个需求也非常常见；比如需要线程异步计算某些数据然后得到结果最终汇总使用。</p>
<p>先来看看如何使用（和 jdk 的类似）：</p>
<p>首先任务是不能实现 <code>Runnable</code> 接口了，毕竟他的 <code>run()</code> 函数是没有返回值的；所以我们改实现一个 <code>Callable</code> 的接口：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7fffd755d053986.jpg" alt=""></p>
<p>这个接口有一个返回值。</p>
<p>同时在提交任务时也稍作改动：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7fffe1162589733.jpg" alt=""></p>
<p>首先是执行任务的函数由 <code>execute()</code> 换为了 <code>submit()</code>，同时他会返回一个返回值 <code>Future</code>，通过它便可拿到线程执行的结果。</p>
<p>最后通过第二步将所有执行结果打印出来：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7ffff5b48143266.jpg" alt=""></p>
<h2 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h2><p>再看具体实现之前先来思考下这样的功能如何实现？</p>
<ul>
<li>首先受限于 <code>jdk</code> 的线程 <code>api</code> 的规范，要执行一个线程不管是实现接口还是继承类，最终都是执行的 <code>run()</code> 函数。</li>
<li>所以我们想要一个线程有返回值无非只能是在执行 <code>run()</code> 函数时去调用一个有返回值的方法，再将这个返回值存放起来用于后续使用。</li>
</ul>
<p>比如我们这里新建了一个 <code>Callable&lt;T&gt;</code> 的接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Callable</span>&lt;<span class="title">T</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 执行任务</div><div class="line">     * <span class="doctag">@return</span> 执行结果</div><div class="line">     */</div><div class="line">    <span class="function">T <span class="title">call</span><span class="params">()</span> </span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>它的 <code>call</code> 函数就是刚才提到的有返回值的方法，所以我们应当在线程的 run() 函数中去调用它。</p>
<p>接着还会有一个 <code>Future</code> 的接口，他的主要作用是获取线程的返回值，也就是 <code>再将这个返回值存放起来用于后续使用</code> 这里提到的<strong>后续使用</strong>。</p>
<p>既然有了接口那自然就得有它的实现 <code>FutureTask</code>，它实现了 <code>Future</code> 接口用于后续获取返回值。</p>
<p>同时实现了 <code>Runnable</code> 接口会把自己变为一个线程。</p>
<p><img src="https://i.loli.net/2019/06/06/5cf7ffffe7dac41090.jpg" alt=""></p>
<p>所以在它的 <code>run()</code> 函数中会调用刚才提到的具有返回值的 <code>call()</code> 函数。</p>
<hr>
<p>再次结合 <code>submit()</code> 提交任务和 <code>get()</code> 获取返回值的源码来看会更加理解这其中的门道。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 有返回值</div><div class="line"> *</div><div class="line"> * <span class="doctag">@param</span> callable</div><div class="line"> * <span class="doctag">@param</span> &lt;T&gt;</div><div class="line"> * <span class="doctag">@return</span></div><div class="line"> */</div><div class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">Future&lt;T&gt; <span class="title">submit</span><span class="params">(Callable&lt;T&gt; callable)</span> </span>&#123;</div><div class="line">    FutureTask&lt;T&gt; future = <span class="keyword">new</span> FutureTask(callable);</div><div class="line">    execute(future);</div><div class="line">    <span class="keyword">return</span> future;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>submit()</code> 非常简单，将我们丢进来的 <code>Callable</code> 对象转换为一个 <code>FutureTask</code> 对象，然后再调用之前的 <code>execute()</code> 来丢进线程池（后续的流程就和一个普通的线程进入线程池的流程一样）。</p>
<blockquote>
<p>FutureTask 本身也是线程，所以可以直接使用 <code>execute()</code> 函数。</p>
</blockquote>
<hr>
<p>而 <code>future.get()</code> 函数中 <code>future</code> 对象由于在 <code>submit()</code> 中返回的真正对象是 <code>FutureTask</code>，所以我们直接看其中的源码就好。</p>
<p><img src="https://i.loli.net/2019/06/06/5cf80005766ef25838.jpg" alt=""></p>
<p>由于 <code>get()</code> 在线程没有返回之前是一个阻塞函数，最终也是通过 <code>notify.wait()</code> 使线程进入阻塞状态来实现的。</p>
<p>而使其从 <code>wait()</code> 中返回的条件必然是在线程执行完毕拿到返回值的时候才进行唤醒。</p>
<p>也就是图中的第二部分；一旦线程执行完毕（<code>callable.call()</code>）就会唤醒 <code>notify</code> 对象，这样 <code>get</code> 方法也就能返回了。</p>
<hr>
<p>同样的道理，<code>ThreadPoolExecutor</code> 中的原理也是类似，只不过它考虑的细节更多所以看起来很复杂，但精简代码后核心也就是这些。</p>
<p>甚至最终使用的 api 看起来都是类似的：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf80006c916e52248.jpg" alt=""></p>
<h1 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h1><p>最后一个是一些新手使用线程池很容易踩坑的一个地方：那就是异常处理。</p>
<p>比如类似于这样的场景：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf8000749e6c64762.jpg" alt=""></p>
<p>创建了只有<strong>一个线程</strong>的线程池，这个线程只做一件事，就是一直不停的 while 循环。</p>
<p>但是循环的过程中不小心抛出了一个异常，巧的是这个异常又没有被捕获。你觉得后续会发生什么事情呢？</p>
<p>是线程继续运行？还是线程池会退出？</p>
<p><img src="https://i.loli.net/2019/06/06/5cf800079d51a22414.jpg" alt=""></p>
<p>通过现象来看其实哪种都不是，线程既没有继续运行同时线程池也没有退出，会一直卡在这里。</p>
<p>当我们 <code>dump</code> 线程快照会发现：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf8000823ad870419.jpg" alt=""></p>
<p>这时线程池中还有一个线程在运行，通过线程名称会发现这是新创建的一个线程（之前是<code>Thread-0</code>，现在是 <code>Thread-1</code>）。</p>
<p>它的线程状态为 <code>WAITING</code> ，通过堆栈发现是卡在了 <code>CustomThreadPool.java:272</code> 处。</p>
<p><img src="https://i.loli.net/2019/06/06/5cf8000872d1f43610.jpg" alt=""></p>
<p>就是卡在了从队列里获取任务的地方，由于此时的任务队列是空的，所以他会一直阻塞在这里。</p>
<p><strong>看到这里，之前关注的朋友有没有似曾相识的感觉。</strong></p>
<p>没错，我之前写过两篇：</p>
<ul>
<li><a href="https://crossoverjie.top/2019/03/12/troubleshoot/thread-gone/">一个线程罢工的诡异事件</a></li>
<li><a href="https://crossoverjie.top/2019/03/26/troubleshoot/thread-gone2/">线程池中你不容错过的一些细节</a></li>
</ul>
<p>线程池相关的问题，当时的讨论也非常<code>“激烈”</code>，其实最终的原因和这里是一模一样的。</p>
<p>所以就这次简版的代码来看看其中的问题：</p>
<p><img src="https://i.loli.net/2019/06/06/5cf80008d46e642627.jpg" alt=""></p>
<p>现在又简化了一版代码我觉得之前还有疑问的朋友这次应该会更加明白。</p>
<p>其实在线程池内部会对线程的运行捕获异常，但它并不会处理，只是用于标记是否执行成功；</p>
<p>一旦执行失败则会回收掉当前异常的线程，然后重新创建一个新的 <code>Worker</code> 线程继续从<strong>队列里取任务然后执行</strong>。</p>
<p>所以最终才会卡在<code>从队列中取任务</code>处。</p>
<p>其实 <code>ThreadPoolExecutor</code> 的异常处理也是类似的，具体的源码就不多分析了，在上面两篇文章中已经说过几次。</p>
<p><strong>所以我们在使用线程池时，其中的任务一定要做好异常处理。</strong></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>这一波下来我觉得线程池搞清楚没啥问题了，总的来看它内部运用了非常多的多线程解决方案，比如：</p>
<ul>
<li><code>ReentrantLock</code> 重入锁来保证线程写入的并发安全。</li>
<li>利用等待通知机制来实现线程间通信（线程执行结果、等待线程池执行完毕等）。</li>
</ul>
<p>最后也学会了：</p>
<ul>
<li>标准的线程池关闭流程。</li>
<li>如何使用有返回值的线程。</li>
<li>线程异常捕获的重要性。</li>
</ul>
<p>最后本文所有源码（结合其中的测试代码使用）：</p>
<p><a href="https://github.com/crossoverJie/JCSprout/blob/master/src/main/java/com/crossoverjie/concurrent/CustomThreadPool.java" target="_blank" rel="external">https://github.com/crossoverJie/JCSprout/blob/master/src/main/java/com/crossoverjie/concurrent/CustomThreadPool.java</a></p>
<p><strong>你的点赞与分享是对我最大的支持</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/concurrent/" rel="tag">#concurrent</a>
          
            <a href="/tags/ThreadPool/" rel="tag">#ThreadPool</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/24/skill/first-blog/" rel="next" title="年轻人的第一篇博客">
                <i class="fa fa-chevron-left"></i> 年轻人的第一篇博客
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/06/13/framework-design/sharding-db-02/" rel="prev" title="分表后需要注意的二三事">
                分表后需要注意的二三事 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#任务完成后的通知"><span class="nav-number">2.</span> <span class="nav-text">任务完成后的通知</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#JDK-的实现"><span class="nav-number">2.1.</span> <span class="nav-text">JDK 的实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#带有返回值的线程"><span class="nav-number">3.</span> <span class="nav-text">带有返回值的线程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#实现原理"><span class="nav-number">3.1.</span> <span class="nav-text">实现原理</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#异常处理"><span class="nav-number">4.</span> <span class="nav-text">异常处理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2019/06/06/concurrent/threadpool-02/';
      var disqus_title = "线程池没你想的那么简单（续）";
      var disqus_url = 'http://crossoverjie.top/2019/06/06/concurrent/threadpool-02/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
